#' Predict Function for lin_reg Objects
#'
#' This function makes predictions based on a 'lin_reg' model.
#'
#' @param object An object of class 'lin_reg'.
#' @param newdata A data frame containing new data for prediction.
#' @return A numeric vector of predictions.
#' @examples
#' devtools::load_all()
#' x <- rnorm(100)
#' y <- 20 * x + 23 + rnorm(100)
#' data <- data.frame(x = x, y = y)
#' model <- lin_reg(y ~ x, data = data)
#' new_data <- data.frame(x = 1:10)
#' predictions <- predict(model, newdata = new_data)
#' print(predictions)
#' plot(data$x, data$y, main = "Actual vs Predicted", xlab = "x", ylab = "y")
#' points(data$x, predictions, col = "red", pch = 19)
#' legend("topright", legend = c("Actual", "Predicted"), col = c("black", "red"), pch = c(1, 19))
#' @export
predict.lin_reg <- function(object, newdata) {
  if (!all(attr(object$terms, "variables")[-1] %in% names(newdata))) {
    stop("New data does not contain all variables used in the model.")
  }

  # 确保 newdata 中的变量与模型中使用的变量相同
  new_x <- model.matrix(object$terms, newdata = newdata, na.action = na.pass)
    # 计算预测值
  predictions <- new_x %*% object$beta
  return(as.vector(predictions))
}
